package com.coder.gaeblogger.manager;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 * @author Chandana
 *
 */
public class BlogManager {
	
	public static PersistenceManager getPMF(){
		return com.coder.gaeblogger.jdo.PMF.get().getPersistenceManager();
	}
	
		
	/**
	 * @param domainClass 	<b>"any domain class, Ex: BlogPost, User"</b>
	 * @param field 		<b>"search field available in domain class"</b>
	 * @param value 		<b>"search field value in domain class"</b>
	 * @return 				<b>domainClass type object</b>
	 */
	public Object getByField(Class<?> domainClass, String field, Object value) {
		PersistenceManager pm = com.coder.gaeblogger.jdo.PMF.get().getPersistenceManager();
		Object obj = null;
		Query query = pm.newQuery(domainClass);
		query.setFilter(field + " == sParam");
		query.declareParameters(value.getClass().getSimpleName() + " sParam");

		List<?> results = (List<?>) query.execute(value);
		if (!results.isEmpty()) {
			obj = results.get(0);
		}
		return obj;
	}
	
	/**
	 * @param domainClass 	<b>"any domain class, Ex: BlogPost.class, User.class"</b>
	 * @param id 			<b>primery key</b>
	 */
	public void delete(Class<?> domainClass,Long id) {
		PersistenceManager pm =	com.coder.gaeblogger.jdo.PMF.get().getPersistenceManager(); 
		pm.deletePersistent(pm.getObjectById(domainClass, id));

	}
	
	/**
	 * @param domainClass 	<b>"any domain class, Ex: BlogPost.class, User.class"</b>
	 * @return 				<b>List of object in type domainClass</b>
	 */
	public List<?> getAll(Class<?> domainClass) {
		PersistenceManager pm = com.coder.gaeblogger.jdo.PMF.get().getPersistenceManager(); 
		Query query = pm.newQuery(domainClass);
		List<?> results = (List<?>) query.execute();
		pm.detachCopyAll(results);

		return results;
	}
	
	/**
	 * @param domain 		<b>"any domain class, Ex: BlogPost.class, User.class"</b>
	 */
	public void save(Object domain) {
		PersistenceManager pm = com.coder.gaeblogger.jdo.PMF.get().getPersistenceManager(); 
		pm.makePersistent(domain);

	}
	
	/**
	 * @param domain 		<b>"any domain class, Ex: BlogPost.class, User.class"</b>
	 */
	public void update(Object domain) {
		PersistenceManager pm = com.coder.gaeblogger.jdo.PMF.get().getPersistenceManager(); 
		pm.makePersistent(domain);

	}
	
	/**
	 * @param domain 		<b>"any domain class, Ex: BlogPost.class, User.class"</b>
	 * @param id 			<b>primery key</b>
	 * @return				<b>domain class type object</b>
	 */
	public Object getById(Class<?> domainClass, Long id) {
		PersistenceManager pm = com.coder.gaeblogger.jdo.PMF.get().getPersistenceManager(); 
		return pm.getObjectById(domainClass,id);
	}

}
